<template>
  <div style="position: relative;"
       class="report_layout">
    <span class="btnBox"
          @click="showDesign"
          v-if="hasEditPermission&& !showMsg&&$hasPermission('sys:report:reportadmin')">
      <i class="el-icon-more showBtn"></i>
    </span>
    <div class="top-toolbar"
         v-if="showMsg&&$hasPermission('sys:report:reportadmin')">
      <div class="top-toolbar-title"></div>
      <div class="top-toolbar-tool">
        <el-button-group style="position:absolute;right:40px;top:6px;">
          <el-button style="height: 24px;padding: 5px 15px;"
                     icon="el-icon-plus"
                     v-if="editMode && hasEditPermission"
                     size="mini"
                     type="success"
                     v-on:click.native='selectedgadgetPop'>{{ $t('add') }}
          </el-button>
          <el-button size="mini"
                     type="primary"
                     style="height: 24px;padding: 5px 15px;"
                     v-if="hasEditPermission"
                     icon="el-icon-edit"
                     v-on:click.native='toggleClick'
                     ref="toggleBtn">{{ editMode ? 'Save' : 'Design' }}
          </el-button>
          <el-button size="mini"
                     style="height: 24px;padding: 5px 15px;"
                     v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')&&false"
                     icon="el-icon-document-copy">{{ $t('custom.reports.clonebtn') }}
          </el-button>
          <el-button size="mini"
                     v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')&&false"
                     icon="el-icon-printer">{{ $t('custom.reports.botbtn') }}
          </el-button>
        </el-button-group>
        <i class="el-icon-circle-close closeBtn"
           @click="showDesign"></i>
      </div>
    </div>
    <div v-loading="loading">
      <div>
        <grid-layout :layout.sync="gadgets"
                     :col-num="12"
                     :row-height="10"
                     :is-draggable="dashbordDefaultSetting.allowDragging"
                     :is-resizable="dashbordDefaultSetting.allowResizing"
                     :vertical-compact="true"
                     :use-css-transforms="true">
          <grid-item v-for="(item,index) in gadgets"
                     :x="item.x"
                     :y="item.y"
                     :w="item.w"
                     :h="item.h"
                     :i="item.i"
                     :key="item.i"
                     :static="item.static"
                     @container-resized="containerResizedEvent"
                     @resized="resizedEvent"
                     @mouseenter.native="mouseEnterModule(index)"
                     @mouseleave.native="mouseLeaveModule(index)">
            <div v-if="editMode&&item&&item.showSetting&&item.showSetting === 'show'"
                 style="height:20px;lineHeight:20px;position:absolute;top:2px;right:2px;z-index:2020;background:#ffffff;">
              &nbsp;
              <i @mouseenter="moveComponent(true)"
                 @mouseleave="moveComponent(false)"
                 :title="$t('custom.move')"
                 class="el-icon-rank"
                 v-if="$hasPermission('sys:report:pageheaderadmin')"
                 style="cursor:pointer;"></i>&nbsp;
              <i v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')"
                 @click="editComponent(item.i)"
                 :title="$t('custom.edit')"
                 class="el-icon-s-operation"
                 style="cursor:pointer;"></i>&nbsp;
              <i @click="closeComponent(item.i)"
                 :title="$t('custom.remove')"
                 v-if="$hasPermission('sys:report:pageheaderadmin')"
                 class="el-icon-close"
                 style="cursor:pointer;"></i>&nbsp;
            </div>
            <template v-if="item.com === 'appstabsgadget'">
              <component :editMode='editMode'
                         :gadgetInfo='item'
                         @dragChanged='gadgetDragChanged'
                         ref="gadgets"
                         @removed='gadgetRemoved'
                         :id='item.i'
                         :pageId='pageId'
                         :businessType='businessTypeForWidget'
                         :reportNameForPage='reportNameForPage'
                         :is="item.com"></component>
            </template>
            <template v-else>
              <component :editMode='editMode'
                         :gadgetInfo='item'
                         @dragChanged='gadgetDragChanged'
                         ref="gadgets"
                         @removed='gadgetRemoved'
                         :id='item.i'
                         :pageId='pageId'
                         :businessType='businessTypeForWidget'
                         :reportNameForPage='reportNameForPage'
                         :is="item.com"></component>
            </template>
          </grid-item>
          <div v-if="gadgets && gadgets.length < 2 "
               style="display: flex;justify-content: center ;align-items:center ;height: 80vh;background: #fff; margin-top:10px;">
            <img :src="$ossLink+'/app/dashboard/dashboard-left.png'"
                 style="height:500px" />
          </div>
        </grid-layout>
      </div>
      <el-dialog :visible.sync="dialog"
                 title="Select Widget"
                 @closed="clearFormData"
                 width="620px">
        <div class="select_widget_filter_condition">
          <el-row>
            <el-col :span="18">
              <div class="filter_condition_lf">
                <div class="filter_condition">Filter</div>
                <div>
                  <el-input placeholder="Search"
                            @input="checkedName"
                            v-model="searchVal">
                    <i slot="prefix"
                       class="el-input__icon el-icon-search"></i>
                  </el-input>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
            </el-col>
          </el-row>
        </div>
        <div class="widget_data_list"
             v-loading="widgetLoading">
          <el-checkbox-group v-model="checkedCities"
                             @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(val,index) in  businessTypeListrecord.slice((currentPage-1)*5,currentPage*5)"
                         :label="val.name"
                         :key="index"
                         :class="'checked'?'el-checkted':''">
              <div class="item_widget">
                 <img style="width:40px;height:40px;margin-right:20px" :src="gadgetTypeImgUrl(val.gadgetType)">
                <div class="item_widget_content">
                  <div>{{val.name}}</div>
                  <div>{{val.description}}</div>
                </div>
                <div class="item_widget_ri"
                     @click.prevent="PreviewWidget(val)">
                  <el-tooltip :open-delay="1000" class="item"
                              effect="dark"
                              :content="$t('preview')"
                              placement="bottom-start">
                    <el-button></el-button>
                  </el-tooltip>
                </div>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div>
          <el-pagination layout="prev, pager, next"
                         :total="businessTypeListrecord.length"
                         :page-size="5"
                         :page-count='currentPage'
                         :current-page='currentPage'
                         @current-change="handleCurrentChange">
          </el-pagination>
        </div>
        <template slot="footer">
          <el-button size="small"
                     @click="dialog = false">{{ $t('Cancel') }}</el-button>
          <el-button type="primary"
                     size="small"
                     @click="addGadgetToPageGroup()">{{ $t('Add') }}</el-button>
        </template>
      </el-dialog>
      <model :showSetting="queryModelDefaultSetting.showSetting"
             @queryModelClosed="queryModelClosed"
             :dataInfo="queryModelDefaultSetting.dataInfo"
             :mappingForm="mappingFormSetting"
             :updateGadget="upgradeGadgetSetting" />
    </div>
    <InterGetStarted :integrationCode="reportIntegrationCode"
                     ref="inter-get-started-dialog" />
  </div>
</template>

<script>
import mixinDashboardViewModule from './dashboard-view-module'
import mixinViewModule from '@/mixins/crud-view-module'
import model from '@/components/gadget/query-model/query-model.vue'
import { dashboardGadgetList } from '@/utils/data-json'
export default {
  mixins: [mixinDashboardViewModule, mixinViewModule],
  data () {
    return {
      reportRelationIntrogrationList: [],
      mixinViewModuleOptions: {
        createdIsNeed: false
      },
      titleTabs: 'title',
      widgetLoading: false,
      currentPage: 1,
      checkedGauge: [],
      dataForm: {
        dataset: ''
      },
      searchVal: '',
      checkedCities: [],
      businessTypeListrecord: [],
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {},
          reuse: true
        }
      }
    }
  },
  components: {
    model
  },
  computed: {
    GadgetList: {
      get () {
        let tempList = []
        tempList = this.userGadgetList
        return tempList
      },
      set (newVal) {
        this.businessTypeListrecord = newVal
      }
    },
    businessTypeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList
    },
    hasEditPermission () {
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:report:edit') ? 1 : 0
      let isCustom = this.businessTypeForWidget === 'Custom' ? 1 : 0
      if (reportadmin + editAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    userGadgetList (val) {
      this.widgetLoading = false
      this.businessTypeListrecord = this.filterHasWidget(val)
    },
    dialog (newVal) {
      if (newVal) this.widgetLoading = true
    },
    '$store.state.bot.routeMeta': function (val) {
      this.getDashboardLayout()
    }
  },
  activated () {
    this.getQureAll()
    if (localStorage.getItem('botdetailpageconfig') !== `${this.slicer.pageid}${this.slicer.botId}`) {
      localStorage.setItem('botdetailpageconfig', `${this.slicer.pageid}${this.slicer.botId}`)
      this.getDashboardLayout()
    }
  },
  methods: {
    gadgetTypeImgUrl (type) {
      let obj = this._.filter(dashboardGadgetList, { key: type })
      return obj[0].imageUrl || ''
    },
    clearFormData () {
      this.currentPage = 1
      this.searchVal = ''
      this.dataForm.dataset = ''
      this.businessTypeListrecord = []
      this.checkedCities = []
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    PreviewWidget (item) {
      this.commandClick(item)
    },
    reportMoreEdit () {
      this.visible = false
      this.$emit('editMoreReportShow', true)
    },
    handleCheckedCitiesChange (value) {
      this.checkedGauge = value
    },
    filterHasWidget (value) {
      let tempList = value
      if (this.businessTypeForWidget !== 'MSPbots Internal') {
        if (this.businessTypeForWidget === 'Template') {
          tempList = this._.reject(tempList, { businessType: 'Custom' })
        }
        tempList = this._.reject(tempList, { businessType: 'MSPbots Internal' })
      }
      let arr = []
      let tempListArr = []
      this.gadgets.forEach(element => {
        arr.push(element.i)
      })
      tempList.forEach(element => {
        if (arr.indexOf(element.gadgetId) === -1) {
          tempListArr.push(element)
        }
      })
      return tempListArr
    },
    checkedName (val) {
      this.currentPage = 1
      if (this.businessTypeForWidget === 'Template') {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.businessType === 'Template').filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      } else {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      }
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    showDesign () {
      this.showMsg = !this.showMsg
    },
    addGadgetToPageGroup () {
      this.filterHasWidget(this.userGadgetList).forEach(ele => {
        if (this.checkedGauge.includes(ele.name)) {
          this.reportRelationIntrogrationList.concat(ele.integrationCode)
          this.addGadgetToPage(ele)
          this.dialog = false
        }
      })
      this.checkedGauge = []
    },
    getIntegrationList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (!(this.gadgets.length === 1 && this.gadgets[0].com === 'pageheadergadget')) {
            for (const key in res.data) {
              if (Object.hasOwnProperty.call(res.data, key)) {
                const element = res.data[key]
                if (this.reportIntegrationCode.length > 0 && (this.reportIntegrationCode.includes(key) && element.sync.group === 2 && this.businessTypeForWidget !== 'MSPbots Internal')) {
                  this.$refs['inter-get-started-dialog'].visible = true
                  break
                }
              }
            }
          }
        }).catch(() => {
        })
    },
    commandClick (row) {
      this.queryModelDefaultSetting.dataInfo.businessId = row.businessId
      this.queryModelDefaultSetting.dataInfo.gadgetId = row.gadgetId
      this.queryModelDefaultSetting.dataInfo.gadgetType = row.gadgetType
      this.queryModelDefaultSetting.dataInfo.gadgetSetting = row.gadgetSetting
      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    mappingFormSetting (to, from) {

    },
    upgradeGadgetSetting () {

    }
  },
  beforeCreate () {
    this.$options.components.InterGetStarted = () => import('../reports/intergrations-get-started/index')
  },
  created () {
    this.getIntegrationList()
  }
}
</script>
<style lang="scss">
.report_layout {
  ::v-deep .select_widget_filter_condition {
    background: url("../../../../assets/select_widget-filter-icon.png");
    background-repeat: no-repeat;
    background-position: center left;
    background-size: 14px 14px;
    padding-left: 20px;
    .filter_condition_lf {
      .filter_condition {
        margin-top: 8px;
        margin-left: 5px;
      }
    }
    .filter_condition_lf > div {
      float: left;
      width: 150px;
      margin-right: 10px;
    }
    .filter_condition_lf > div:nth-child(1) {
      width: auto;
    }
  }
  .select_widget_filter_condition::after {
    content: ".";
    clear: both;
    display: block;
    overflow: hidden;
    height: 0;
  }
  .widget_data_list {
    margin-top: 20px;
    min-height: 20px;
    .el-checkbox-group {
      > .is-checked {
        border: 1px solid #138dc7;
      }
    }
    .el-checkbox {
      display: block;
      margin-right: 0;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      margin-top: 10px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .el-checkbox__input {
        display: block;
        width: 54px;
        text-align: center;
      }
      .el-checkbox__label {
        flex: 1;
        display: block;
        height: 100%;
        padding-left: 0;
        .item_widget {
          // background: url("../../../../assets/grid.png");
          background-size: 48px 48px;
          background-repeat: no-repeat;
          background-position: left center;
          height: 100%;
          // padding-left: 54px;
          padding-top: 5px;
          padding-bottom: 5px;
          display: flex;
          justify-content: space-around;
          align-items: center;
          min-height: 70px;
          .item_widget_content {
            flex: 1;
            height: 100%;
            padding-right: 10px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            > div {
              white-space: pre-wrap;
              word-break: break-word;
            }

            > div:nth-child(1) {
              color: #000;
              font-size: 14px;
            }
            > div:nth-child(2) {
              font-size: 14px;
              color: rgba(0, 0, 0, 0.49);
            }
          }
          .item_widget_ri {
            float: right;
            width: 53px;
            height: 100%;
            text-align: center;
            .item {
              height: 14px;
              width: 14px;
              border: 0;
              background: url("../../../../assets/select_widget_eye.png");
              background-size: 14px 14px;
              background-repeat: no-repeat;
              background-position: center;
            }
          }
          position: relative;
        }
        .item_widget::after {
          content: "";
          clear: both;
          display: block;
          overflow: hidden;
          position: absolute;
          right: 53px;
          border-right: 1px solid #f0f0f0;
          height: 80%;
        }
      }
    }
    .el-checkbox::after {
      content: ".";
      clear: both;
      display: block;
      overflow: hidden;
      height: 0;
    }
  }
  .el-pagination {
    text-align: center;
  }
  .layoutTitle {
    font-size: 12px;
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .layoutTitle:hover {
    overflow: visible;
  }

  .vue-grid-item.vue-grid-placeholder {
    background: #f2f8ff;
    border: 1px solid #38f;
    opacity: 1;
  }

  .layoutJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
  }

  .eventsJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
    height: 100px;
    overflow-y: scroll;
  }

  .columns {
    -moz-columns: 120px;
    -webkit-columns: 120px;
    columns: 120px;
  }

  .vue-resizable-handle {
    z-index: 5000;
    position: absolute;
    width: 20px;
    height: 20px;
    bottom: 0;
    right: 0;
    background: url("");
    background-position: bottom right;
    padding: 0 3px 3px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: se-resize;
  }

  .editmode:not(.vue-grid-placeholder) {
    border: 1px solid #38f;
    opacity: 0.5;
  }

  .vue-grid-item.resizing {
    opacity: 0.9;
  }

  .vue-grid-item .no-drag {
    height: 100%;
    width: 100%;
  }

  .vue-grid-item .minMax {
    font-size: 12px;
  }

  .vue-grid-item .add {
    cursor: pointer;
  }

  .vue-draggable-handle {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>")
      no-repeat;
    background-position: bottom right;
    padding: 0 8px 8px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: pointer;
  }

  .layout-item {
    text-align: center;
    margin-bottom: 15px;
    padding: 0 5px;
  }

  .layout-item .bottom {
    position: relative;
    margin-top: 15px;
  }

  .layout-item .bottom span {
    display: block;
    float: left;
    width: 50%;
    margin-top: 12px;
    text-align: left;
  }

  .layout-item .bottom button {
    padding-top: 0;
  }

  .top-toolbar {
    position: relative;
    margin-top: -15px;
    height: 35px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    background-color: #fff;
    margin-left: -15px;
    padding-top: 10px;
    width: calc(100% + 30px);
  }

  .top-toolbar .top-toolbar-title {
    padding-left: 25px;
  }

  .btnBox {
    height: 16px;
    padding: 0px 10px;
    background: #c4ebf3;
    position: absolute;
    top: -15px;
    right: 24px;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
  }

  .showBtn {
    font-size: 18px;
    color: #00c4ed;
  }

  .closeBtn {
    font-size: 18px;
    position: absolute;
    top: 8px;
    right: 11px;
  }
}
</style>
